<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加房源信息</title>
</head>
<body>
<h1>发布房源</h1>
<a href="/index">返回首页</a>
<form id="addForm">
    房屋描述:<input type="text" name="houseDesc"/><br />
    户型:<select name="houseType.typeId">
            <option value="">选择</option>
        </select><br />
    租金:<input type="text" name="monthlyRent"/><br />
    <input type="submit" value="提交"/>
    <input type="reset" value="重置"/>
</form>
<script type="text/javascript" th:src="@{/jquery-3.7.1.js}"></script>
<script type="text/javascript">
    $(function() {
        loadSelectData();
        bindEvent();
    });

    function bindEvent(){
        $("#addForm").submit(function(res){
            var houseDesc = $("input[name=houseDesc]").val();
            var monthlyRent = $("input[name=monthlyRent]").val();
            console.log(houseDesc, monthlyRent);
            if (!houseDesc) {
                alert("房屋描述必填!");
                return false;
            }
            if (!monthlyRent) {
                alert('租金格式错误!');
                return false;
            }
            // console.log(isNaN(Number(monthlyRent)));
            if (isNaN(Number(monthlyRent))) {
                alert('租金格式错误!');
                return false;
            }
            $.post("/houseInfo", $("#addForm").serialize(), function(res){
                console.log(res);
                alert(res['msg']);
                if (res['code'] == 200) {
                    window.location.href = '/index';
                }
            }, "json");
            return false;
        });
    }

    function loadSelectData(){
        $.getJSON("/houseType", function(res){
            console.log(res);
            var strSelect = '';
            for (var i = 0; i < res.length; i++) {
                strSelect += '<option value="'+res[i]['typeId']+'">'+res[i]['typeName']+'</option>';
            }
            $("[name^=houseType]").html(strSelect);
        });
    }
</script>
</body>
</html>